<template>
  <div class="outbound-confirmation-new">
    <div class="header-buttons">
      <button class="btn" @click="goBack">
        <span class="back-icon">←</span>返回
      </button>
      <button class="btn" @click="saveData">保存</button>
      <button class="btn">数据暂存</button>
      <button class="btn">草稿箱</button>
      <button class="btn import-btn">导入</button>
    </div>

    <div class="page-title">
      <h2>{{ isEditMode ? '编辑出库确认' : '出库确认' }}</h2>
    </div>

    <div class="content-box">
      <div class="section basic-info">
        <div class="section-title">基本信息</div>
        <div class="form-grid">
          <div class="form-row">
            <div class="form-item required">
              <label>单据主题：</label>
              <input 
                type="text" 
                class="form-control clickable" 
                v-model="formData.subject"
                @click="goToDetail"
                :placeholder="isEditMode ? '' : '点击输入单据主题'"
              />
            </div>
            <div class="form-item">
              <label>出库类型：</label>
              <input type="text" class="form-control" v-model="formData.outboundType" readonly />
            </div>
            <div class="form-item required">
              <label>出库库管：</label>
              <div class="search-input">
                <input type="text" class="form-control" v-model="formData.manager" />
                <span class="search-icon">🔍</span>
              </div>
            </div>
            <div class="form-item">
              <label>确认时间：</label>
              <div class="date-input">
                <input type="text" class="form-control" v-model="formData.confirmationTime" readonly />
                <span class="calendar-icon">📅</span>
              </div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>关联项目：</label>
              <div class="search-input">
                <input type="text" class="form-control" v-model="formData.project" />
                <span class="search-icon">🔍</span>
              </div>
            </div>
            <div class="form-item">
              <label>关联单位名称：</label>
              <div class="search-input">
                <input type="text" class="form-control" v-model="formData.relatedUnit" />
                <span class="search-icon">🔍</span>
              </div>
            </div>
            <div class="form-item">
              <label>关联销售合同：</label>
              <div class="search-input">
                <input type="text" class="form-control" v-model="formData.salesContract" />
                <span class="search-icon">🔍</span>
              </div>
            </div>
            <div class="form-item"></div>
          </div>
        </div>
      </div>

      <div class="section shipping-address">
        <div class="section-title">收货地址</div>
        <div class="form-grid">
          <div class="form-row">
            <div class="form-item">
              <label>收货人：</label>
              <input type="text" class="form-control" v-model="formData.receiver" />
            </div>
            <div class="form-item">
              <label>座机电话：</label>
              <input type="text" class="form-control" v-model="formData.telephone" />
            </div>
            <div class="form-item">
              <label>手机号码：</label>
              <input type="text" class="form-control" v-model="formData.mobile" />
            </div>
            <div class="form-item"></div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label>所在省份：</label>
              <input type="text" class="form-control" v-model="formData.province" />
            </div>
            <div class="form-item">
              <label>所在市区：</label>
              <input type="text" class="form-control" v-model="formData.city" />
            </div>
            <div class="form-item full-width">
              <label>详细地址：</label>
              <input type="text" class="form-control" v-model="formData.address" />
            </div>
          </div>
        </div>
      </div>

      <div class="section products">
        <div class="section-title">产品明细</div>
        <div class="toolbar">
          <button class="btn">增行</button>
          <button class="btn">复制行</button>
          <button class="btn">放大</button>
          <button class="btn">删行</button>
          <button class="btn">导入</button>
          <button class="btn">导入模板</button>
        </div>

        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th class="checkbox-col"><input type="checkbox" /></th>
                <th class="seq-col">序号</th>
                <th class="required">产品名称</th>
                <th>产品编号</th>
                <th>规格型号</th>
                <th>单位</th>
                <th class="required">预计出库数量</th>
                <th>库存信息</th>
                <th class="required">出库仓库</th>
                <th>到货日期</th>
                <th>包装方式</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in productList" :key="item.id">
                <td><input type="checkbox" /></td>
                <td>{{ index + 1 }}</td>
                <td>
                  <input type="text" class="table-input" v-model="item.productName" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.productCode" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.specification" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.unit" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.quantity" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.stockInfo" readonly />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.warehouse" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.deliveryDate" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.packagingMethod" />
                </td>
                <td>
                  <input type="text" class="table-input" v-model="item.remark" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="form-footer">
          <div class="form-item">
            <label>确认出库总量：</label>
            <input type="text" class="form-control" :value="calculateTotalQuantity()" readonly />
          </div>
        </div>
      </div>

      <div class="section attachments">
        <div class="upload-buttons">
          <button class="btn">批量上传</button>
        </div>
        <table class="file-table">
          <thead>
            <tr>
              <th>文件名称</th>
              <th>文件大小</th>
              <th>上传人</th>
              <th>上传时间</th>
              <th></th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <!-- 文件列表为空 -->
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 判断是否为编辑模式
const isEditMode = ref(false)
const recordId = ref('')

// 表单数据
const formData = ref({
  // 基本信息
  subject: '',                // 单据主题
  outboundType: '',          // 出库类型
  outboundList: '',          // 出库申请单
  confirmationTime: '',       // 确认时间
  project: '',               // 关联项目
  manager: '',               // 出库库管
  
  // 收货地址信息
  relatedUnit: '',           // 关联单位名称
  salesContract: '',         // 关联销售合同
  receiver: '',              // 收货人
  telephone: '',             // 座机电话
  mobile: '',               // 手机号码
  province: '',             // 所在省份
  city: '',                // 所在市区
  address: ''              // 详细地址
})

// 产品明细数据
const productList = ref<any[]>([
  // 默认显示10行空数据
  ...Array(10).fill(0).map((_, index) => ({
    id: `temp-${index}`,
    productName: '',
    productCode: '',
    specification: '',
    unit: '',
    quantity: '',
    stockInfo: '',
    warehouse: '',
    deliveryDate: '',
    packagingMethod: '',
    remark: ''
  }))
])

// 初始化页面，检查是否为编辑模式
onMounted(() => {
  // 从路由参数中获取记录ID
  const id = route.query.id as string
  console.log('路由参数:', route.query)
  
  // 检查是否有传递数据
  if (route.query.data) {
    try {
      // 解析传递的行数据
      const encodedData = route.query.data as string
      console.log('编码后的数据:', encodedData)
      
      const decodedData = decodeURIComponent(encodedData)
      console.log('解码后的数据:', decodedData)
      
      const rowData = JSON.parse(decodedData)
      console.log('解析后的数据对象:', rowData)
      
      console.log('开始反填数据，原始数据：', rowData)
      
      // 反填表单数据
      formData.value = {
        ...formData.value,
        // 基本信息
        subject: rowData.subject || '',                    // 单据主题
        outboundType: rowData.type || '申请直接出库',     // 出库类型
        outboundList: rowData.outboundType || '',         // 出库申请单
        confirmationTime: rowData.confirmTime || '',       // 确认时间
        project: rowData.relatedProject || '',            // 关联项目
        manager: rowData.manager || '',                   // 出库库管
        
        // 收货地址信息 - 如果没有，保持默认空值
        relatedUnit: '',        // 关联单位名称
        salesContract: '',      // 关联销售合同
        receiver: '',           // 收货人
        telephone: '',          // 座机电话
        mobile: '',            // 手机号码
        province: '',          // 所在省份
        city: '',             // 所在市区
        address: ''           // 详细地址
      }
      
      console.log('反填后的表单数据：', formData.value)
      
      // 解析产品明细数据
      parseProductDetails(rowData)
      
      // 如果是修改操作，设置为编辑模式
      if (id && id !== 'new') {
        isEditMode.value = true
        recordId.value = id
      }
    } catch (e) {
      console.error('解析路由数据失败:', e)
    }
  } else if (id && id !== 'new') {
    // 没有传递数据但有ID，按原逻辑加载数据
    isEditMode.value = true
    recordId.value = id
    loadOutboundData(id)
  }
})

// 加载出库单数据
const loadOutboundData = async (id: string) => {
  try {
    // 这里替换为实际的API调用
    // const response = await fetch(`/api/outbound/${id}`)
    // const data = await response.json()
    
    // 模拟数据加载
    setTimeout(() => {
      // 模拟数据
      const mockData = {
        subject: '出库单-' + id,
        outboundType: '申请直接出库',
        outboundList: 'OL-' + id,
        confirmationTime: '2025-04-09 10:17:30',
        project: '项目-' + id,
        manager: '张研',
        relatedUnit: '单位-' + id,
        salesContract: 'SC-' + id,
        receiver: '张三',
        telephone: '010-12345678',
        mobile: '13800138000',
        province: '北京市',
        city: '海淀区',
        address: '科技园路88号'
      }
      
      console.log('加载的模拟数据:', mockData)
      
      // 更新表单数据
      Object.assign(formData.value, mockData)
    }, 100)
  } catch (error) {
    console.error('加载出库单数据失败:', error)
  }
}

// 返回列表页面
const goBack = () => {
  router.push('/warehouse/outbound-confirmation')
}

// 保存数据
const saveData = () => {
  // 表单验证
  if (!formData.value.subject) {
    alert('请输入单据主题')
    return
  }
  
  const saveUrl = isEditMode.value 
    ? `/api/outbound/${recordId.value}` // 更新现有记录
    : '/api/outbound' // 创建新记录
    
  // 这里添加实际的保存逻辑
  console.log('保存数据到:', saveUrl, formData.value)
  
  // 保存成功后的处理
  alert(isEditMode.value ? '更新成功!' : '保存成功!')
  
  // 保存成功后返回列表页面
  router.push('/warehouse/outbound-confirmation')
}

// 跳转到详情页
const goToDetail = () => {
  if (formData.value.subject.trim()) {
    router.push({
      path: '/warehouse/outbound-detail',
      query: { 
        id: isEditMode.value ? recordId.value : 'new',
        subject: formData.value.subject 
      }
    })
  }
}

// 处理表单中的日期字段格式化
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toISOString().split('T')[0]
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateString
  }
}

// 计算出库总量
const calculateTotalQuantity = () => {
  let total = 0
  productList.value.forEach(item => {
    const quantity = parseFloat(item.quantity)
    if (!isNaN(quantity)) {
      total += quantity
    }
  })
  return total.toFixed(2)
}

// 从路由参数中解析产品明细数据
const parseProductDetails = (rowData: any) => {
  console.log('解析产品明细数据:', rowData)
  
  // 如果有产品明细数据，解析并填充
  if (rowData.products && Array.isArray(rowData.products)) {
    // 使用传入的产品数据
    productList.value = rowData.products.map((product: any, index: number) => ({
      id: product.id || `imported-${index}`,
      productName: product.name || '',
      productCode: product.code || '',
      specification: product.specification || '',
      unit: product.unit || '',
      quantity: rowData.quantity || '',  // 使用主表的数量
      stockInfo: product.stockInfo || '',
      warehouse: product.warehouse || '',
      deliveryDate: product.deliveryDate ? formatDate(product.deliveryDate) : '',
      packagingMethod: product.packagingMethod || '',
      remark: product.remark || ''
    }))
    
    // 如果产品数据少于10行，添加空行到10行
    const currentLength = productList.value.length
    if (currentLength < 10) {
      const emptyRows = Array(10 - currentLength).fill(0).map((_, index) => ({
        id: `temp-${currentLength + index}`,
        productName: '',
        productCode: '',
        specification: '',
        unit: '',
        quantity: '',
        stockInfo: '',
        warehouse: '',
        deliveryDate: '',
        packagingMethod: '',
        remark: ''
      }))
      
      productList.value = [...productList.value, ...emptyRows]
    }
  }
}
</script>

<style scoped>
.outbound-confirmation-new {
  font-family: Arial, sans-serif;
  padding: 0;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-buttons {
  background-color: #f0f0f0;
  padding: 8px;
  display: flex;
  border-bottom: 1px solid #ddd;
  gap: 5px;
}

.back-icon {
  margin-right: 4px;
  font-size: 14px;
}

.right-align {
  margin-left: auto;
}

.btn {
  margin-right: 5px;
  padding: 4px 12px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 2px;
  cursor: pointer;
  font-size: 12px;
}

.import-btn {
  margin-right: auto;
}

.page-title {
  text-align: center;
  margin: 15px 0;
}

.page-title h2 {
  font-size: 18px;
  font-weight: normal;
  margin: 0;
}

.content-box {
  margin: 0 10px;
}

.section {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 3px;
  margin-bottom: 15px;
}

.section-title {
  background-color: #f9f9f9;
  padding: 8px 15px;
  font-size: 14px;
  border-bottom: 1px solid #e0e0e0;
}

.form-grid {
  padding: 15px;
}

.form-row {
  display: flex;
  margin-bottom: 10px;
}

.form-item {
  display: flex;
  align-items: center;
  width: 25%;
  padding: 0 5px;
}

.full-width {
  width: 50%;
}

.form-item label {
  width: 90px;
  text-align: right;
  padding-right: 10px;
  font-size: 12px;
}

.required label::before {
  content: "* ";
  color: red;
}

.form-control {
  flex: 1;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 2px;
  font-size: 12px;
  height: 28px;
}

.clickable {
  cursor: pointer;
}

.clickable:hover {
  background-color: #f5f5f5;
  border-color: #ccc;
}

.search-input {
  position: relative;
  flex: 1;
  display: flex;
}

.search-input .form-control {
  width: 100%;
}

.search-icon {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

.date-input {
  position: relative;
  flex: 1;
  display: flex;
}

.date-input .form-control {
  width: 100%;
}

.calendar-icon {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}

.toolbar {
  padding: 8px;
  border-bottom: 1px solid #e0e0e0;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.data-table th, .data-table td {
  border: 1px solid #e0e0e0;
  padding: 6px;
  text-align: center;
}

.data-table th {
  background-color: #f9f9f9;
  font-weight: normal;
}

.checkbox-col {
  width: 30px;
}

.seq-col {
  width: 40px;
}

.form-footer {
  padding: 10px;
  display: flex;
}

.attachments {
  margin-bottom: 50px;
}

.upload-buttons {
  padding: 8px;
  border-bottom: 1px solid #e0e0e0;
}

.file-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.file-table th, .file-table td {
  border: 1px solid #e0e0e0;
  padding: 6px;
  text-align: left;
}

.file-table th {
  background-color: #f9f9f9;
  font-weight: normal;
}

.table-input {
  width: 100%;
  border: none;
  background: transparent;
  padding: 2px 4px;
  font-size: 12px;
}

.table-input:focus {
  outline: none;
  background-color: #f0f7ff;
}

.table-input:hover {
  background-color: #f5f5f5;
}
</style>